import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Role } from './entities/role.entity';
import { In, Like, Repository } from 'typeorm';
import { StatusText } from 'src/types/enum';
import { Menu } from '../menus/entities/menu.entity';
import { SearchRoleDto } from './dto/search-role.dto';

@Injectable()
export class RoleService {

  constructor(
    @InjectRepository(Role) private roleRepository: Repository<Role>,
    @InjectRepository(Menu) private menuRepository: Repository<Menu>,
  ) { }

  async create(createRoleDto: CreateRoleDto) {
    const result = await this.roleRepository.save(createRoleDto);
    return {
      code: 200,
      msg: StatusText.CREATE_SUCCESS,
      data: result
    };
  }

  async findSearch(searchRoleDto: SearchRoleDto) {
    let search = {
      skip: (searchRoleDto.currentPage - 1) * searchRoleDto.pageSize,
      take: searchRoleDto.pageSize,
      where: {},
      relations: ['accounts', 'menus'] // 这里必须加
    }
    if (searchRoleDto.roleName) {
      search.where = {
        roleName: Like(`%${searchRoleDto.roleName}%`)
      }
    }
    const result = await this.roleRepository.find(search);
    return {
      code: 200,
      msg: StatusText.SEARCH_SUCCESS,
      data: {
        list: result
      }
    };
  }

  async findAll() {
    let search = {
      relations: ['accounts', 'menus'] // 这里必须加
    }
    const result = await this.roleRepository.find(search);
    return {
      code: 200,
      msg: StatusText.SEARCH_SUCCESS,
      data: {
        list: result
      }
    };
  }

  async findOne(id: number) {
    const result = await this.roleRepository.findOne({
      where: {
        id
      },
      relations: ['accounts', 'menus'] // 这里必须加
    });
    return {
      code: 200,
      msg: StatusText.DETAIL_SUCCESS,
      data: result
    };
  }

  async update(id: number, updateRoleDto: UpdateRoleDto) {
    const result = await this.roleRepository.update(id, updateRoleDto);
    return {
      code: 200,
      msg: StatusText.UPDATE_SUCCESS,
      data: result
    };
  }

  async remove(id: number) {
    const result = await this.roleRepository.delete({ id });
    return {
      code: 200,
      msg: StatusText.DELETE_SUCCESS,
      data: result
    };
  }

  async assignMenus(role_id: number, menuIds: number[]): Promise<ResponseData<Role | null>> {

    const role = await this.roleRepository.findOne({ where: { id: role_id } });

    if (!role) {
      return {
        code: 404,
        msg: "角色不存在",
        data: null
      }
    }
    const menus = await this.menuRepository.findBy({ id: In(menuIds) })
    role.menus = menus;

    const result = await this.roleRepository.save(role);

    return {
      code: 200,
      msg: "菜单分配成功",
      data: result
    }
  }
}
